import sensor
import time
import network
import socket
from pyb import LED

SSID = "xcz"  # 网络 SSID
KEY = "12345678"  # 网络密钥
HOST = "49.235.120.243"  # 使用第一个可用的接口
PORT = 8082  # 任意非特权端口

# 初始化传感器
sensor.reset()
sensor.set_framesize(sensor.QVGA)
sensor.set_pixformat(sensor.RGB565)

# 初始化wlan模块并连接到网络
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, KEY)

# 显示红灯并每秒连接一次网络直至连接成功
led = LED(1)
led.on()
while not wlan.isconnected():
    wlan.connect(SSID, KEY)
    time.sleep_ms(1000)
    print("wifi connect err")
led.off()

print("WiFi Connected ", wlan.ifconfig())

def video_send(client):
    clock.tick()
    frame = sensor.snapshot()
    # 去畸变
    frame.lens_corr(strength=1.8, zoom=1.0)
    cframe = frame.to_jpeg(quality=35, copy=False)
    # 报头
    header = ("Content-Length: " + str(len(cframe)) + "\r\n") + ("tick: " + str(clock.fps()) + "\r\n\r\n")
    client.sendall(header)
    client.sendall(cframe)
    print(clock.fps())

clock = time.clock()

while True:
    try:
        # 创建套接字
        videoclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # videoclient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

        # 阻塞等待
        videoclient.setblocking(True)
        sockaddr = socket.getaddrinfo(HOST, PORT)[0][-1]
        # 执行任务

        # 等待连接并亮蓝灯
        led = LED(3)
        led.on()
        videoclient.connect(sockaddr)
        # 连接完成,关闭蓝色状态灯
        led.off()

        while True:
            video_send(videoclient)

    except OSError as e:
        videoclient.close()
        print('client except')
        continue

